package com.jia.sconsumer;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@EnableCircuitBreaker
@EnableZuulProxy
@EnableFeignClients
@EnableDiscoveryClient
@RestController
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ProviderClient providerClient;

    @HystrixCommand(fallbackMethod = "countd")
    @RequestMapping("/countr")
    public String countr() {
        return this.restTemplate.getForObject("http://sprovider/count", String.class);
    }

    @RequestMapping("/countf")
    public String countf() {
        return providerClient.count();
    }

    @RequestMapping("/countd")
    public String countd() {
        return "countd";
    }

    @RequestMapping("/")
    public String home() {
        return "sconsumer";
    }

    @RequestMapping("/health")
    public String health() {
        return "ok";
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @FeignClient("sprovider")
    public interface ProviderClient {

        @RequestMapping(value = "/count", method = RequestMethod.GET)
        String count();
    }
}
